import {
  Upload,
  Icon,
  message,
  Button,
  Drawer,
  Table,
  Popconfirm,
  notification,
  Tooltip,
} from 'antd';
import React from 'react';
import BaseComponent from '@/components/BaseComponent';
import { connect } from 'dva';
import request from 'umi-request';
const { Dragger } = Upload;
@connect(({ user, detaileddatareporting, loading }) => ({
  currentUser: user.currentUser,
  isRunning: loading.effects['detaileddatareporting/execFileParse'],
}))
export default class ImageDragger extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      fileList: [],
      visible: false,
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '状态',
          key: 'isUploading',
          render: (text, record) => {
            const { isUploading } = record;
            if (isUploading) {
              return <span style={{ color: '#E94738' }}>上传中...</span>;
            } else {
              return <span style={{ color: '#32A44E' }}>上传成功</span>;
            }
          },
        },
        {
          title: '操作',
          key: 'operate',
          render: (text, record, index) => {
            return (
              <Popconfirm
                title="确定执行当前操作吗?"
                onConfirm={() => {
                  this.handleDelFileItem(record);
                }}
              >
                <Button type="link">移除</Button>
              </Popconfirm>
            );
          },
        },
      ],
    };
  }
  handleDelFileItem = index => {
    const { fileList } = this.state;
    fileList.splice(index, 1);
    this.setState({
      fileList: [...fileList],
    });
  };
  handleOnUploadChange = info => {
    const { status } = info.file;
    if (status !== 'uploading') {
      // 上传中
    }
    if (status === 'done') {
      const response = info.file.response;

      const { fileList } = this.state;
      const obj = fileList.find(each => each.name == info.file.name);
      //上传完成
      if (obj) {
        obj.isUploading = false;
        const { data } = response;
        if (data) {
          obj.fileId = data.fileId;
          obj.absolute_url = response.data.filePath;
          obj.url = response.data.filePath.split('/images')[1];
          obj.key = this.generateId();
        }
      }
      console.log(fileList);
      this.setState({
        fileList: [...fileList],
      });

      // console.log(`${info.file.name} file uploaded successfully.`);
    } else if (status === 'error') {
      this.errorMessage(`${info.file.name} 上传失败`);
      // console.log(`${info.file.name} file upload failed.`);
    }
  };

  /**
   * excel文件上传前的回调
   * @param {*} file
   * @param {*} fileList
   */
  handleBeforeUpload = (file, fileList) => {
    const { type } = file;
    const fileName = file.name.split('.')[0];

    // const pattern1 = /^([\u4e00-\u9fa5a-zA-Z]+)-(\d{4}-\d{2}-\d{2})-(内镜)$/;
    const pattern2 = /^([\u4e00-\u9fa5a-zA-Z]+)-(\d{4}\d{2}\d{2})-(病理)$/;
    const pattern1 = /^([\u4e00-\u9fa5a-zA-Z]+)-(\d{4}\d{2}\d{2})-(内镜)$/;

    console.log(pattern1.test(fileName));

    if (!pattern1.test(fileName) && !pattern2.test(fileName)) {
      if (!pattern1.test(fileName)) {
        file.response = '设置内镜报告单文件名为:姓名-内镜诊疗日期-内镜';
      } else {
        file.response = '设置内镜报告单文件名为:姓名-内镜诊疗日期-病理';
      }
      file.status = 'error';

      return false;
    }

    if (type != 'image/jpeg' && type != 'image/png' && type != 'application/pdf') {
      file.status = 'error';
      file.response = '只支持上传jpg/png/pdf格式的文件';
      return false;
    } else {
      const { fileList } = this.state;
      const obj = {
        name: file.name,
        type: file.type,
        isUploading: true,
      };
      fileList.push(obj);
      this.setState({ fileList });
      return true;
    }
  };
  showDrawer = () => {
    this.setState({
      visible: true,
    });
  };
  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  closeDrawer = () => {
    this.setState({
      visible: false,
    });
  };

  submit = () => {
    if (this.state.fileList == 0) {
      notification.open({
        message: '请选择需要上传的文件',
        type: 'error',
      });
      return;
    }

    request('/api/cdcerservice/v1/cerSysteminitImportInfo/imageEscalation', {
      method: 'POST',
      data: {
        user: this.props.currentUser.id,
        data: JSON.stringify(this.state.fileList),
      },
    }).then(() => {
      notification.open({
        message: '上传成功',
      });
      this.setState({
        visible: false,
      });
    });
  };

  submitHandler = () => {
    const { targetName, imgSumbit } = this.props;
    const { fileList } = this.state;
    imgSumbit(targetName, fileList);
    this.setState({
      visible: false,
    });
  };
  render() {
    const props = {
      name: 'file',
      multiple: true,
      action: `/api/file/file/uploadFile4Report?user=${this.props.currentUser.id}`,
      accept: '.jpg,.jpeg,.png,.pdf',
      headers: {
        authorization: 'authorization-text',
      },
      showUploadList: false,
      onChange: this.handleOnUploadChange,
      beforeUpload: this.handleBeforeUpload,
    };
    const { visible, columns, fileList } = this.state;
    const { files } = this.props;

    return (
      <div>
        <Button type="primary" onClick={this.showDrawer}>
          图片上报
        </Button>

        <Drawer
          visible={visible}
          title="图片上报"
          placement="right"
          width={'55%'}
          maskClosable={true}
          closable={true}
          onClose={this.onClose}
        >
          <Tooltip>
            <span style={{ color: 'red' }}>
              上传说明
              <br />
              1、通过内镜或病理工作站获取内镜报告单和病理报告单，报告单支持JPG、PNG、PDF格式。
              <br />
              2、报告文件支持两种命名规则,规则如下:
              <br />
              3、设置内镜报告单文件名为:姓名-内镜诊疗日期-内镜，如: 张三-20220101-内镜。
              <br />
              4、设置病理报告单文件名为:姓名-病理报告日期-病理，如: 张三-20220101-病理。
              <br />
              5、设置内镜报告单文件名为:姓名-内镜号(报告单编号)-内镜号，如: 张-C2123456-内镜号。
              <br />
              6、设置病理报告单文件名为: 姓名-病理号(报告单编号)-病理号，如: 张三-BL2123456-病理号。
              <br />
              7、每张图片代表一个病人的内镜或病理信息，系统支持批量上传。
              <br />
            </span>
          </Tooltip>
          <Dragger {...props}>
            <p className="ant-upload-drag-icon">
              <Icon type="inbox" />
            </p>
            <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
          </Dragger>
          <Table columns={columns} rowKey="fileId" dataSource={fileList}></Table>
          <div
            style={{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button onClick={this.closeDrawer} type="danger" style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={this.submit} type="primary">
              提交
            </Button>
          </div>
        </Drawer>
      </div>
    );
  }
}
